/**   
 * @Title: PostMagicInfo.java 
 * @Package com.esun.services.magic 
 * @Description: TODO(执行后台发送数据) 
 * @author Miko baoz@500wan.com   
 * @date 2011-4-7 下午04:47:32  
 */
package com.esun.util.magic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.esun.config.Config;
import com.esun.config.DistributionChannels;
import com.esun.model.UserInfo;
import com.esun.util.log.EDebug;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * @ClassName: PostMagicInfo
 * @Description: TODO(执行后台发送数据)
 * @author Miko baoz@500wan.com
 * @date 2011-4-7 下午04:47:32
 * 
 */
public class PostMagicInfo {

	// private static final String TEST = "test";
	// private static final String ACTION = "action";

	private static final String EVENT = "event";
	private static final String PRODUCT = "product";
	private static final String USER_NAME = "username";
	private static final String CHANNEL = "channel";
	private static final String APPVERSION = "version";
	private static final String PLATFORM = "platform";
	private static final String SYS_VER = "sysversion";
	private static final String SCREEN = "screenreso";
	private static final String MAGIC_NUM = "serial";

	private static final String NET_TYPE = "nettype";
	private static final String LOCATION = "location";
	private static final String LAT = "lat";
	private static final String LNG = "lng";

	private Context context;

	private String channel;

	private String magicNum;

	private String sysVersion;

	private String userName;

	private String screen;

	private int retryTimes = 0;

	// / added by kuroky
	private String nettype;
	private String location = "";
	private Double lat;
	private Double lng;

	public PostMagicInfo(Context context) {

		this.context = context;

		getInfos();
		doSend();
	}

	private void getInfos() {

		magic.setContext(this.context);

		channel = DistributionChannels.QUDAO;

		/** 2011-12-30 by city 更新magicNum 为 mac地址 */
		if (UserInfo.getUserInfo().getWlanMac() == Config.NULLMARK) {
			magicNum = magic.getMagicNum();
		} else {
			magicNum = UserInfo.getUserInfo().getWlanMac();
		}
		sysVersion = magic.getPhoneRelease();
		userName = magic.getUserName();
		screen = magic.getScreenInfo();

		nettype = getNetType();

		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		Location locat = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		// 获取经纬度
		if (locat != null) {
			lat = locat.getLatitude() * 1E6 / 1E6;
			lng = locat.getLongitude() * 1E6 / 1E6;

			// System.out.println(lat) ;
			// System.out.println(lng) ;

			Geocoder gc = new Geocoder(context, Locale.getDefault());
			// System.out.println("***************$^^^^^^^^^^^^^^*******************")
			// ;

			try {
				List<Address> listAddress = gc.getFromLocation(lat, lng, 1);
				if (listAddress.size() > 0) {

					// System.out.println("**********************************************")
					// ;
					Address address = listAddress.get(0);

					// System.out.println(address);

					location = address.getLocality();

				}
			} catch (IOException e) {

				e.printStackTrace();
			}
		}
	}

	private boolean postMsg() {

		HttpPost httpRequest = new HttpPost(Config.MAGIC_ADD);

		List<NameValuePair> params = new ArrayList<NameValuePair>();

		try {

			EDebug.o(this, "============================ ELK Magic Info ======================================");
			// params.add(new BasicNameValuePair(TEST, "false"));
			// EDebug.o(this,TEST + " : " + "true");

			params.add(new BasicNameValuePair(EVENT, "1"));

			params.add(new BasicNameValuePair(PRODUCT, "rabbit"));
			EDebug.o(this, PRODUCT + " : " + "rabbit");

			// params.add(new BasicNameValuePair(ACTION, "userinfo"));
			// EDebug.o(this,ACTION + " : " + "userinfo");

			params.add(new BasicNameValuePair(CHANNEL, channel));
			EDebug.o(this, CHANNEL + " : " + channel);

			params.add(new BasicNameValuePair(MAGIC_NUM, magicNum));
			EDebug.o(this, MAGIC_NUM + " : " + magicNum);

			params.add(new BasicNameValuePair(SYS_VER, sysVersion));
			EDebug.o(this, SYS_VER + " : " + sysVersion);

			params.add(new BasicNameValuePair(USER_NAME, userName));
			EDebug.o(this, USER_NAME + " : " + userName);

			params.add(new BasicNameValuePair(SCREEN, screen));
			EDebug.o(this, SCREEN + " : " + screen);

			String versionName = context.getPackageManager().getPackageInfo("com.esun.ui", 0).versionName;

			params.add(new BasicNameValuePair(APPVERSION, versionName));
			EDebug.o(this, APPVERSION + " : " + versionName);

			params.add(new BasicNameValuePair(PLATFORM, "android"));
			EDebug.o(this, PLATFORM + " : " + "android");

			params.add(new BasicNameValuePair(NET_TYPE, nettype));
			EDebug.o(this, NET_TYPE + " : " + nettype);

			params.add(new BasicNameValuePair(LOCATION, location));
			EDebug.o(this, LOCATION + " : " + location);
			// System.out.println(location);

			params.add(new BasicNameValuePair(LAT, String.valueOf(lat)));
			EDebug.o(this, LAT + " : " + String.valueOf(lat));
			// System.out.println(lat);

			params.add(new BasicNameValuePair(LNG, String.valueOf(lng)));
			EDebug.o(this, LNG + " : " + String.valueOf(lng));
			// System.out.println(lng);

			EDebug.o(this, "============================ ELK Magic Info ======================================");

			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			new DefaultHttpClient().execute(httpRequest);

			return true;

		} catch (Exception e) {
			return false;
		}

	}

	private void doSend() {

		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();

				while (retryTimes <= 5) {

					if (postMsg()) {
						break;
					} else {
						retryTimes++;
					}
				}
			}
		}.start();
	}

	/**
	 * 获取入网方式方法
	 * 
	 * @return
	 */
	private String getNetType() {

		ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectManager != null) {

			NetworkInfo netInfo = connectManager.getActiveNetworkInfo();

			if (netInfo != null) {

				int netType = netInfo.getType();

				if (netType == ConnectivityManager.TYPE_MOBILE) {

					return "mobile";

				} else {

					return "wifi";

				}

			}
		}
		// 获取不到入网方式
		return "--";

	}
}
